<?php

namespace liketp\response;

use liketp\Request;
use liketp\Response;

class Jsonp extends Response
{
    protected $request;
    protected $contentType = 'application/javascript';

    public function __construct(Request $request, $data, int $code)
    {
        $this->init($data, $code);
        $this->request = $request;
    }
    public function output($data)
    {
        $callFn = $this->request->param($this->_varCallFn, $this->defaultCallFn);
        if ($data instanceof \Closure) {
            $data = $data();
        }
        $type = strtolower(gettype($data));
        if (in_array($type, ['array', 'object'])) {
            $data = json_encode($data);
        } else if (is_string($data)) {
            $data = '"' . $data . '"';
        } else if (is_null($data)) {
            $data = 'null';
        } else if ($type == 'boolean') {
            $data = $data ? 'true' : 'false';
        }
        return $callFn . '(' . $data . ')';
    }
}
